import React, {useCallback, useEffect, useRef, useState} from "react";
import {SystemName} from "./js/constants";
import styled from "styled-components";
import {withRouter} from "react-router-dom";
import {Button, Modal, message, notification} from "antd";
import ChangePassword from "../ChangePassword";
import {changePassword} from "../../api/users";
import ws from "../../ws";
import {wsAlarmCountUrl as alarmWsUrl, wsUnhandleAlarmUrl} from "../../api/request";
import './Header.css'
import alarmMp3 from '../../asserts/alarm.mp3'

let FlexDiv = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 22px;
`;

let Img = styled.img`
  width: 24px;
  height: 24px;
  border: 1px solid rgb(238, 238, 238);
  border-radius: 50%;
  vertical-align: -7px;
  margin-right: 9px;
`;

let InfoItem = styled.div`
  &::after {
    content: "";
    margin-right: 10px;
    border-right: 1px solid #dadada;
    padding-right: 10px;
    color: #0cace6;
  }
  &:last-child::after {
    margin: 0;
    padding: 0;
    border: none;
  }
  & {
		display: inline-block;
		color: #999999;
		cursor: pointer;
	}
`;

const notifyCount = 3;
let notifyNum = 0;

function Header(props) {
    const [showModal, setShowModal] = useState(false)
    const popRef = useRef()
    const onRef = (ref) => popRef.current = ref
    const alarmAudio = useRef()
    const onModalOk = (event) => {
        // console.log('event', event);
        const canPost = popRef.current.validateFields();
        const formValue = popRef.current.getFormValue()
        // console.log(formValue);
        if (canPost) {
            changePassword(formValue)
                .then(() => {
                    message.info("密码修改成功!3秒后退出")
                    localStorage.removeItem("userInfo")
                    localStorage.removeItem("token")
                    setTimeout(() => props.history.push("/"), 3000)
                })
                .finally(() => {
                    setShowModal(false)
                })
        }
    }

    const showNotify = useCallback((alarm) => {
        const key = notifyNum.toString()
        if (notifyNum >= notifyCount) {
            notification.close((notifyNum - notifyCount).toString())
        }

        notification.error({
            message: `${alarm.channel_name} 异常，请核查处理!`,
            onClick: () => {
                console.log(props.history)
                props.history.replace({
                    pathname: `/Home/MonitoringDetail/${alarm.channel}`,
                    // state: {channelId: alarm.channel}
                    // query: {channelId: alarm.channel}
                });
               /* if (window.location.href.indexOf('/Home/MonitoringDetail') !== -1) {
                    window.location.reload()
                }*/
                // window.location.href.toString().lastIndexOf('/')
                /*window.location.href='http://localhost:3000/#/Home/MonitoringDetail/129'*/
                notification.close(key)
            },
            key,
            duration: 1800
        });
        alarmAudio.current.play()
        notifyNum++
    }, [])

    useEffect(() => {
        ws.addConnect(wsUnhandleAlarmUrl)
        ws[wsUnhandleAlarmUrl].onmessage = event => {
            const unHandleAlarms = JSON.parse(event.data);
            // console.log('aaa', unHandleAlarms)
            showNotify(unHandleAlarms)
        };
        return () => {
            ws.deleteConnect(wsUnhandleAlarmUrl)
        }
    }, [])


    return (
        <FlexDiv>
            {/*<Button onClick={() => {
				showNotify({channel_name: notifyNum,})
			}}>测试</Button>*/}
            <audio src={alarmMp3} style={{visibility: false}} ref={alarmAudio}/>
            <div>{SystemName}</div>
            <div style={{fontSize: 14}}>
                <InfoItem>
                    {/*<Img src={require("../../asserts/face_default.png")}></Img>*/}
                    {
                        JSON.parse(localStorage.getItem("userInfo"))?.username
                    }
                </InfoItem>
                <InfoItem onClick={() => {
                    localStorage.removeItem("token")
                    localStorage.removeItem("userInfo")
                    props.history.push('/login')
                }}>退出</InfoItem>
                <InfoItem onClick={() => {
                    setShowModal(true)
                }}>修改密码</InfoItem>
            </div>
            <Modal
                destroyOnClose
                visible={showModal}
                onCancel={() => {
                    setShowModal(false)
                }}
                onOk={onModalOk}

            >
                <ChangePassword onRef={onRef}/>
            </Modal>
        </FlexDiv>
    );
}

export default withRouter(Header);
